/**
 * 
 */
package com.googlecode.android_di;

import java.util.ArrayList;
import java.util.List;

import net.nycjava.skylight1.dependencyinjection.DependencyInjectingObjectFactory;
import net.nycjava.skylight1.dependencyinjection.DependencyInjector;
import android.app.Activity;
import android.app.Application;
import android.content.SharedPreferences;

import com.google.inject.Module;

/**
 * @author Panxiaobo
 * 
 */
public class DiApplication extends Application {
    private volatile DependencyInjector injector;

    /* default */DependencyInjector getInjector() {
        if (injector == null) {
            synchronized (this) {
                if (injector == null) {
                    DependencyInjectingObjectFactory factory = new DependencyInjectingObjectFactory();
                    internalConfigure(factory);
                    injector = new DependencyInjector(factory);
                }
            }
        }
        return injector;
    }

    private void internalConfigure(DependencyInjectingObjectFactory factory) {
        factory.registerImplementationObject(SharedPreferences.class,
                DiApplication.this.getSharedPreferences("PREF", 0));
        configure(factory);
    }

    public void configure(DependencyInjectingObjectFactory factory) {
        List<Module> list = new ArrayList<Module>();
        addApplicationModules(list);

        for (Module m : list) {
            DiModule module = (DiModule) m;
            module.factory = factory;
            module.invokeConfigure();
        }
    }

    protected void addApplicationModules(List<Module> modules) {
    }

    public static void injectActivity(Activity anObject) {
        injectBean(anObject);
        SimpleRoboguice.injectActivity(anObject);
    }

    private static void injectBean(Activity anObject) {
        DiApplication app = (DiApplication) anObject.getApplication();
        app.getInjector().injectDependenciesForClassHierarchy(anObject);
    }

}
